package com.example.nacosdemo.component;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.example.nacosdemo.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class CustomBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.info("BlockExceptionHandler BlockException==============:{}", e.getRule());
        Result result = null;
        if (e instanceof FlowException){
            result = Result.error(100, "服务限流了");
        }else if (e instanceof DegradeException){
            result = Result.error(101, "服务降级");
        }else if (e instanceof ParamFlowException){
            result = Result.error(102, "热点参数限流");
        }else if (e instanceof SystemBlockException){
            result = Result.error(103, "触发系统限流");
        }else if (e instanceof AuthorityException){
            result = Result.error(104, "授权规则不通过");
        }
        response.setStatus(500);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("utf-8");
        new ObjectMapper().writeValue(response.getWriter(), result);
    }
}
